package com.lw.common.customview.item_decoration

import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * @description:列表 条目之间的间距
 * @author: yuan
 * @date: 2023/3/3/0003
 */
class ItemOffsetDecoration(private val mItemOffset: Int, private val spanCount: Int) : RecyclerView.ItemDecoration() {
    constructor(context: Context, itemOffsetId: Int, spanCount: Int) : this(context.resources.getDimensionPixelSize(itemOffsetId), spanCount)

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val childAdapterPosition = parent.getChildAdapterPosition(view)
        outRect.bottom = mItemOffset
        //列数
        val column = childAdapterPosition % spanCount
        if (column == 0) {
            // 第一列左右边距
            outRect.left = mItemOffset
            outRect.right = mItemOffset / 2
        } else if (column == spanCount - 1) {
            outRect.left = mItemOffset / 2
            outRect.right = mItemOffset
        } else {
            // 除了第一列，其佘设置右边距
            outRect.left = mItemOffset / 2
            outRect.right = mItemOffset / 2
        }
        //行数
        val row = childAdapterPosition / spanCount
        if (row == 0) {
            outRect.top = mItemOffset
        }
    }
}
